package com.yuyou.fn.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.activity.entity.ActivityCampusSession;
import com.yuyou.fn.activity.entity.ActivityRegSituation;
import com.yuyou.fn.activity.entity.ActivityTarget;
import com.yuyou.fn.activity.service.IActivityCampusService;
import com.yuyou.fn.activity.service.IActivityCampusSessionService;
import com.yuyou.fn.activity.service.IActivityRegSituationService;
import com.yuyou.fn.activity.service.IActivityTargetService;
import com.yuyou.fn.activity.vo.ActivityCampusDetailVo;
import com.yuyou.fn.activity.vo.ActivityCampusQueryVo;
import com.yuyou.fn.activity.vo.ActivityNumVo;
import com.yuyou.fn.activity.vo.ActivitySessionNumVo;
import com.yuyou.fn.analyze.service.IDataStatisticsService;
import com.yuyou.fn.analyze.service.IIndexStatisticsService;
import com.yuyou.fn.analyze.vo.*;
import com.yuyou.fn.common.constant.ClassLevelEnum;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.service.ISiteConfigService;
import com.yuyou.fn.common.service.ISmsService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.Threads;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.*;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.entity.BusTeam;
import com.yuyou.fn.platform.entity.Oauth;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.IAccessTokenService;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.platform.service.IBusTeamService;
import com.yuyou.fn.platform.service.IOauthService;
import com.yuyou.fn.portal.entity.CourseFilterCondConfig;
import com.yuyou.fn.portal.service.IConfigService;
import com.yuyou.fn.portal.service.IOuterCourseClassService;
import com.yuyou.fn.portal.service.IRecommendRecordService;
import com.yuyou.fn.portal.vo.OuterCourseClassQueryVo;
import com.yuyou.fn.portal.vo.RecommendRecordDetailVo;
import com.yuyou.fn.portal.vo.SimpleCourseClass;
import com.yuyou.fn.report.service.IMergeStudentRegDetailService;
import com.yuyou.fn.report.vo.PeriodQueryRegVo;
import com.yuyou.fn.report.vo.RegRelativceQueryVo;
import com.yuyou.fn.vo.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


/**
 * Created by wens on 16/10/24.
 */

@Controller
@RequestMapping(value="/api/m/t")
public class MTeacherApiController extends ApiBaseController  {

    static final String KEY_PRE="rank:%s:%s:%s:%s";

    @Resource
    private ITeacherService teacherService ;

    @Resource
    private IOauthService oauthService ;

    @Resource
    private IAccessTokenService accessTokenService ;

    @Resource
    private IPeriodService periodService ;

    @Resource
    private ICourseClassService courseClassService ;

    @Resource
    private IClassLectureService classLectureService ;

    @Resource
    private IBaseGradeService baseGradeService ;

    @Resource
    private IBaseSubjectService baseSubjectService ;

    @Resource
    private ITeacherRemunerationService teacherRemunerationService ;

    @Resource
    private ITeacherContinueClassStatService teacherContinueClassStatService ;

    @Resource
    private IContinueClassStatService continueClassStatService ;

    @Resource
    private IStudentService studentService ;

    @Resource
    private IBusTeamService busTeamService ;

    @Resource
    private IAreaTeamService areaTeamService ;

    @Resource
    private RedisTemplate redisTemplate ;

    @Resource
    private ISiteConfigService siteConfigService ;

    @Resource
    private ISmsService smsService ;

    @Resource
    private IDataStatisticsService dataStatisticsService;


    @Resource
    private IMergeStudentRegDetailService mergeStudentRegDetailService;

    @Resource
    private IStudentRefundService studentRefundService;

    @Resource
    private ICampusService campusService;

    @Resource
    private IIndexStatisticsService indexStatisticsService;

    @Resource
    private IOuterCourseClassService outerCourseClassService;

    @Resource
    private IRecommendRecordService recommendRecordService;

    @Resource
    private IConfigService configService;

    @Resource
    private IActivityCampusService activityCampusService;

    @Resource
    private IActivityCampusSessionService activityCampusSessionService;

    @Resource
    private IActivityRegSituationService activityRegSituationService;

    @Resource
    private IActivityTargetService activityTargetService;

    @ApiOperation("微信登录")
    @RequestMapping("/wx/login")
    @ResponseBody
    public ReturnResult<TeacherLoginSuccessVo> wxLogin(@RequestParam("openId") String openId ) {
        Oauth oauth = oauthService.findByRoleOpenId(2, openId);
        if(oauth == null ){
            return ReturnResult.fail("未绑定");
        }

        Teacher teacher = teacherService.findById(oauth.getUserId());

        if(teacher == null ){
            return ReturnResult.fail("未绑定");
        }

        if (teacher.getStatus()!=1){
            return ReturnResult.fail("该教师已离职");
        }
        String accessToken = accessTokenService.generateToken(oauth.getUserId(),teacher.getTeacherName(),"teacher" );
        return  ReturnResult.success(new TeacherLoginSuccessVo(teacher, accessToken ));
    }

    @ApiOperation("微信登录（教师id）")
    @RequestMapping("/wx/loginByTeacherId")
    @ResponseBody
    public ReturnResult<TeacherLoginSuccessVo> loginByTeacherId(@RequestParam("teacherId") Long teacherId){
        Oauth oauth = oauthService.findByUserId(teacherId);
        if(oauth == null ){
            return ReturnResult.fail("未绑定");
        }

        Teacher teacher = teacherService.findById(oauth.getUserId());

        if(teacher == null ){
            return ReturnResult.fail("未绑定");
        }

        if (teacher.getStatus()!=1){
            return ReturnResult.fail("该教师已离职");
        }
        String accessToken = accessTokenService.generateToken(oauth.getUserId(),teacher.getTeacherName(),"teacher" );
        return  ReturnResult.success(new TeacherLoginSuccessVo(teacher, accessToken ));
    }

    @ApiOperation("微信绑定老师信息")
    @RequestMapping("/wx/bind")
    @ResponseBody
    public ReturnResult<Void> bind(@RequestParam("openId") String openId , @RequestParam(value = "name" ) String name , @RequestParam(value = "idNo") String idNo, @RequestParam(value = "authenticationCode") String authenticationCode ) {
        Teacher teacher = teacherService.findTeacherByAuthenticationCode(authenticationCode);

        if (StringUtils.isEmpty(openId)){
            return ReturnResult.fail("openId为空！");
        }
        if(teacher == null){
            return ReturnResult.fail("提交的识别码不正确");
        }
        if (teacher.getStatus()!=1){
            return ReturnResult.fail("该教师已离职");
        }

        if(!teacher.getTeacherName().equals(name) || !teacher.getIdNo().equals(idNo) ){
            return ReturnResult.fail("提交的信息验证不正确");
        }

        oauthService.saveOauth(2,teacher.getTeacherId(), openId , 1 );
        return  ReturnResult.success("OK");
    }

    @ApiOperation("微信绑定老师信息")
    @RequestMapping("/wx/bindWithPhoneNo")
    @ResponseBody
    public ReturnResult<List<Teacher>> bindWithPhoneNo(@RequestParam(value = "areaTeamId",required = false) Long areaTeamId,@RequestParam("openId") String openId , @ApiParam(value = "手机号码",required = true) @RequestParam("phoneNo") String phoneNo , @ApiParam(value = "短信验证码",required = true) @RequestParam(value = "code" ) String code ) {
        oauthService.unbind(openId,2 );
        List<Teacher> teachers = teacherService.findOnJobTeacherByPhoneNo(phoneNo,areaTeamId);
        if(Utils.checkListEmpty(teachers)){
            return ReturnResult.fail("无法找到对应的老师信息，或者该老师已离职");
        }
        if (teachers.size()>1){
            List<Long> areaTeamIds = BeanUtils.toList(teachers, "areaTeamId");
            List<AreaTeam> areaTeamList=areaTeamService.findByIds(areaTeamIds,"areaTeamId","name");
            return ReturnResult.fail("该号码有多个区域，请选择一个区域登录",-1,areaTeamList);
        }

        if( !smsService.validate(phoneNo, code) ){
            throw new BusException("手机验证码不正确");
        }

        oauthService.saveOauth(2,teachers.get(0).getTeacherId(), openId , 1 );

        return  ReturnResult.success(teachers);
    }

    @ApiOperation("微信解绑老师信息")
    @RequestMapping("/wx/unbind")
    @ResponseBody
    public ReturnResult<TeacherLoginSuccessVo> bind(@RequestParam("openId") String openId, HttpServletRequest request ) {
        oauthService.unbind(openId,2 );
        return  ReturnResult.success("OK");
    }



    @ApiOperation("老师端配置")
    @RequestMapping("/config")
    @ResponseBody
    public ReturnResult<TeacherConfigVo> config(HttpServletRequest request) {
        Teacher teacher = getTeacher(request);
        DataPermission dataPermission=this.getDataPermission(request);
        Period currentPeriod = periodService.findCurrentPeriod(teacher.getAreaTeamId());
        Period nextPeriod = periodService.findNextPeriod(currentPeriod.getPeriodId());
        Period maxPeriod=periodService.findMaxPeriod(teacher.getAreaTeamId());
        List<Period> periodList = periodService.findNearPeriod(teacher.getAreaTeamId(), 12);
        List<BaseGrade> baseGradeList = baseGradeService.findAllFromCache();
        List<BaseSubject> subjectList = baseSubjectService.findAllFromCache();
        List<Teacher> teacherList=teacherService.findListByAreaTeamId(teacher.getAreaTeamId(),"teacherId","teacherName");
        List<Campus> campuses=campusService.findByIdsAndStateAndAreaTeamIds(1,Arrays.asList(teacher.getAreaTeamId()));

        Long recommendNum=recommendRecordService.countRecommendRecordByUserId(teacher.getTeacherId());
        ClassLevelEnum[] all = ClassLevelEnum.values();
        List<LevelVo> levelList=new ArrayList<>();
        for (int i=1;i<all.length;i++){
            ClassLevelEnum classLevelEnum=all[i];
            LevelVo levelVo=new LevelVo();
            levelVo.setLevelName(classLevelEnum.name());
            levelVo.setValue(classLevelEnum.ordinal());
            levelList.add(levelVo);
        }
        List<Integer> years =new ArrayList<>(2);
        Integer year=Integer.parseInt(maxPeriod.getPeriodName().substring(0,4));
        years.add(year-1);
        years.add(year);

        List<Map<String,Object>> allTeacherList=new ArrayList<>(teacherList.size());
        for (Teacher teacher1:teacherList){
            Map<String,Object> teacherMap=new HashMap<>();
            teacherMap.put("teacherName",teacher1.getTeacherName());
            teacherMap.put("teacherId",teacher1.getTeacherId());
            teacherMap.put("pingyin",Utils.toPinyin(teacher1.getTeacherName()));
            allTeacherList.add(teacherMap);
        }



        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("currentPeriod",currentPeriod);
        resultMap.put("nextPeriod",nextPeriod);
        resultMap.put("periodList",periodList);
        resultMap.put("gradeList",baseGradeList);
        resultMap.put("subjectList",subjectList);
        resultMap.put("campues",campuses);
        resultMap.put("levelList",levelList);
        resultMap.put("teacherList",allTeacherList);
        resultMap.put("years",years);
        resultMap.put("recommendNum",recommendNum);
        if (dataPermission!=null){
            List<Campus> permissionCampuses=campusService.findByIds(dataPermission.getCampusIds()==null?new ArrayList<>():dataPermission.getCampusIds());
            resultMap.put("permissionCampuses",permissionCampuses);
        }
    //    TeacherConfigVo teacherConfigVo=new TeacherConfigVo(levelList,currentPeriod ,nextPeriod,periodList, baseGradeList ,subjectList , Arrays.asList(2017,2018) ,campuses,teacherList);
        return  ReturnResult.success(resultMap);
    }

    @ApiOperation("老师标签")
    @RequestMapping("/teacherTags")
    @ResponseBody
    public ReturnResult<String[]> teacherTags() {
        String teacherTags = siteConfigService.getConfigValueFromCache("teacher_tags");
        return  ReturnResult.success(teacherTags.split(","));
    }



    @ApiOperation("我任教的课程班")
    @RequestMapping("/myTeachingCourseClass")
    @ResponseBody
    public ReturnResult<Page<CourseClass>> myTeachingClass(@RequestParam("periodId") Long periodId , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,HttpServletRequest request) {
        Page<CourseClass> page  = courseClassService.findMyTeachingCourseClass(getTeacherId(request),periodId,pageNo ,pageSize );
        return  ReturnResult.success(page);
    }

    @ApiOperation("推荐课程班")
    @RequestMapping("/suggestCourseClass")
    @ResponseBody
    public ReturnResult<List<CourseClassWithTeacherVo>> suggestCourseClass(@RequestParam("periodId") Long periodId ,@RequestParam(value = "limit" , defaultValue = "10") int limit , HttpServletRequest request) {
        List<CourseClass> courseClassList = courseClassService.suggestCourseClassForTeacher(periodId , getTeacherId(request),limit );
        List<CourseClassWithTeacherVo> list  = fillTeacher(courseClassList);
        return  ReturnResult.success(list);
    }

    @ApiOperation("任课老师学生续读情况")
    @RequestMapping("/findTeacherContinueRead")
    @ResponseBody
    public ReturnResult<TeacherContinueReadVo> findTeacherContinueRead(@RequestParam("periodId") Long periodId , @RequestParam(value = "bigLectureNum",defaultValue = "5")Integer bigLectureNum, HttpServletRequest request) {
        Teacher teacher = getTeacher(request);
        TeacherContinueReadVo teacherContinueReadVo=dataStatisticsService.findTeacherContinueRead(teacher.getTeacherId(),periodId,bigLectureNum);
        return  ReturnResult.success(teacherContinueReadVo);
    }

    @ApiOperation("任课老师班级详情")
    @RequestMapping("/findClassStudentReadState")
    @ResponseBody
    public ReturnResult<TeacherContinueReadVo> findClassStudentReadState(@RequestParam("classId") Long classId , @RequestParam(value = "bigLectureNum",defaultValue = "5")Integer bigLectureNum, HttpServletRequest request) {
        Teacher teacher = getTeacher(request);
        ClassStudentReadState classStudentReadState=dataStatisticsService.findClassStudentReadState(teacher.getTeacherId(),classId,bigLectureNum);
        return  ReturnResult.success(classStudentReadState);
    }


    @ApiOperation("班主任学生续读情况")
    @RequestMapping("/findSeniorCompletionRate")
    @ResponseBody
    public ReturnResult<SeniorCompletionRateVo> findSeniorCompletionRate(@RequestParam("periodId") Long periodId , HttpServletRequest request) {
        Teacher teacher = getTeacher(request);
        TeacherQueryVo teacherQueryVo=new TeacherQueryVo();
        teacherQueryVo.setTeacherId(teacher.getTeacherId());
        RegRelativceQueryVo regRelativceQueryVo=new RegRelativceQueryVo();
        regRelativceQueryVo.setRecordChargingStatus(2);
        //regRelativceQueryVo.setBigRecordLectureNum(5);
        Page<SeniorCompletionRateVo> seniorCompletionRateVoPage=indexStatisticsService.findSeniorComletionRateVoPage(teacherQueryVo,null,Arrays.asList(periodId),null,1,1);
        if (seniorCompletionRateVoPage.getRecords()!=null && seniorCompletionRateVoPage.getRecords().size()>0){
            SeniorCompletionRateVo seniorCompletionRateVo=seniorCompletionRateVoPage.getRecords().get(0);
            return  ReturnResult.success(seniorCompletionRateVo);
        }
        return  ReturnResult.success("");
    }


    @ApiOperation("班主任学生续读情况详情")
    @RequestMapping("/findSeniorStudentReadState")
    @ResponseBody
    public ReturnResult<List<StudentReadState>> findSeniorStudentReadState(@RequestParam("periodId") Long periodId , HttpServletRequest request) {
        Teacher teacher = getTeacher(request);
        List<StudentReadState> studentReadStateList=dataStatisticsService.findSeniorStudentReadState(teacher.getTeacherId(),periodId);
        return  ReturnResult.success(studentReadStateList);
    }


    @ApiOperation("查询课程班")
    @RequestMapping("/queryCourseClass")
    @ResponseBody
    public ReturnResult<Page<CourseClassWithTeacherVo>> queryCourseClass(@RequestParam(value = "campusId",required = false)Long campusId,@RequestParam("periodId") Long periodId ,@RequestParam(value = "gradeId" , required = false) Long gradeId ,@RequestParam(value = "subjectId" , required = false ) Long subjectId , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,HttpServletRequest request) {
        Teacher teacher = getTeacher(request);
        CourseClassQueryVo courseClassQueryVo = new CourseClassQueryVo();
        courseClassQueryVo.setGradeId(gradeId);
        courseClassQueryVo.setSubjectId(subjectId);
        courseClassQueryVo.setPeriodId(periodId);
        courseClassQueryVo.setStatus(1);
        courseClassQueryVo.setOrderByStartCourseTime(true);
        courseClassQueryVo.setCampusId(campusId);
        courseClassQueryVo.setAreaTeamId(teacher.getAreaTeamId());
        Page<CourseClass> page = courseClassService.findCourseClassByQuery(courseClassQueryVo,pageNo, pageSize);
        Page<CourseClassWithTeacherVo> nPage = Utils.newPage(page);
        nPage.setRecords(fillTeacher(page.getRecords()));
        return  ReturnResult.success(nPage);
    }


    @ApiOperation("课程班详情")
    @RequestMapping("/courseClassDetail")
    @ResponseBody
    public ReturnResult<CourseClass> courseClassDetail(@RequestParam("classId") Long classId ) {
        CourseClass courseClass = courseClassService.findById(classId);
        return  ReturnResult.success(courseClass);
    }

    @ApiOperation("课程班讲列表")
    @RequestMapping("/classLectureList")
    @ResponseBody
    public ReturnResult<List<ClassLecture>> classLectureList(@RequestParam("classId") Long classId ) {
        List<ClassLecture> classLectureList = classLectureService.findClassLectureByClassId(classId);
        return  ReturnResult.success(classLectureList);
    }

    @ApiOperation("将要考勤信息")
    @RequestMapping("/willAttendingInfo")
    @ResponseBody
    public ReturnResult<AttendingInfoVo> willAttendingInfo(HttpServletRequest request) {
        Long teacherId  = getTeacherId(request);
        //查询正在考勤的讲
        ClassLecture classLecture = classLectureService.findAttendingClassLecture(teacherId);

        if(classLecture == null ){
            return ReturnResult.success() ;
        }

        CourseClass courseClass = courseClassService.findById(classLecture.getClassId());
        List<AttendClassRecord> attendClassRecordList = classLectureService.findAttendClassRecordByClassLectureId(classLecture.getClassLectureId());

        return  ReturnResult.success(new AttendingInfoVo(courseClass,classLecture,attendClassRecordList));
    }

    @ApiOperation("保存考勤详情")
    @RequestMapping(value = "/saveAttendanceRecordDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveAttendanceRecordDetail(@RequestParam("classLectureId") Long classLectureId , @RequestParam("details") String detailsStr, HttpServletRequest request) {

        List<AttendClassRecordUpdateVo> details = JSONObject.parseObject(detailsStr, new TypeReference<List<AttendClassRecordUpdateVo>>() {
        });
        classLectureService.updateAttendClassRecord(classLectureId , details,ClassLecture.AttendanceRoleEnum.人工.ordinal());
        return ReturnResult.success("OK");
    }

    @ApiOperation("查询考勤")
    @RequestMapping(value = "/queryAttendance", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<AttendanceVo>> queryAttendance(@RequestParam("date") String date , HttpServletRequest request) {
        Long teacherId  = getTeacherId(request);
        List<ClassLecture> classLectureList = classLectureService.findClassLectureByTeacherIdClassDate(teacherId, Utils.parseDate(date, "yyyy-MM-dd"));

        List<Long> classIds = BeanUtils.toList(classLectureList, "classId");

        List<CourseClass> courseClassList = courseClassService.findByIds(classIds);
        Map<Long,CourseClass> courseClassMap =  BeanUtils.toMap(courseClassList,"classId");

        List<AttendanceVo> list = new ArrayList<>(classLectureList.size());

        for(ClassLecture classLecture : classLectureList ){
            CourseClass courseClass = courseClassMap.get(classLecture.getClassId());
            if(courseClass.getStatus() == 0 || courseClass.getStatus() == 2 ){
                continue;
            }
            list.add(new AttendanceVo(courseClass,classLecture ));
        }
        return ReturnResult.success(list);
    }

    @ApiOperation("获取考勤信息")
    @RequestMapping("/attendingInfo")
    @ResponseBody
    public ReturnResult<AttendingInfoVo> attendingInfo(@RequestParam("classLectureId") Long classLectureId , HttpServletRequest request) {

        ClassLecture classLecture = classLectureService.findById(classLectureId);

        if(classLecture == null ){
            return ReturnResult.success() ;
        }

        CourseClass courseClass = courseClassService.findById(classLecture.getClassId());
        List<AttendClassRecord> attendClassRecordList = classLectureService.findAttendClassRecordByClassLectureId(classLecture.getClassLectureId());

        return  ReturnResult.success(new AttendingInfoVo(courseClass,classLecture,attendClassRecordList));
    }

    @ApiOperation("老师课表")
    @RequestMapping(value = "/classSchedule", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassScheduleVo>> classSchedule(@RequestParam(value = "classTime" ) Long classTime , @RequestParam("timeOrientation" ) Integer timeOrientation , @RequestParam(value = "limit",defaultValue = "50") int limit  , HttpServletRequest request ) {
        List<ClassLecture> classLectureList = classLectureService.findClassLectureByTeacherIdTime(getTeacherId(request), new Date(classTime),timeOrientation,limit );

        List<ClassScheduleVo> classScheduleVoList = new ArrayList<>(classLectureList.size());
        List<Long> classIds = BeanUtils.toList(classLectureList,"classId");
        List<CourseClass> courseClassList = courseClassService.findByIds(classIds);
        Map<Long,CourseClass> courseClassMap = BeanUtils.toMap(courseClassList,"classId") ;
        for(ClassLecture classLecture : classLectureList ){
            CourseClass courseClass = courseClassMap.get(classLecture.getClassId());
            if(courseClass == null || courseClass.getStatus() == 0 || courseClass.getStatus() == 2 ){
                continue;
            }
            classScheduleVoList.add(new ClassScheduleVo(courseClass,classLecture ));
        }
        return ReturnResult.success(classScheduleVoList);
    }

    @ApiOperation("我的课酬和课时统计")
    @RequestMapping(value = "/myClassRemuneration", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassRemunerationVo>> myClassRemuneration(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {

        List<TeacherRemuneration> teacherRemunerationList = teacherRemunerationService.findMyClassRemuneration(periodId, getTeacherId(request));
        Map<Long, ClassRemunerationVo> stat = toClassRemuneration(teacherRemunerationList);

        return ReturnResult.success(new ArrayList<ClassRemunerationVo>(stat.values()));
    }

    @ApiOperation("我的课时、讲数、人次汇总")
    @RequestMapping(value = "/aggregateMyClassRemuneration", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<AggregateTeacherRemunerationVo> aggregateMyClassRemuneration(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {

        List<TeacherRemuneration> teacherRemunerationList = teacherRemunerationService.findMyClassRemuneration(periodId, getTeacherId(request));

        AggregateTeacherRemunerationVo aggregateTeacherRemunerationVo = new AggregateTeacherRemunerationVo();
        aggregateTeacherRemunerationVo.setAmount(BigDecimal.ZERO);
        aggregateTeacherRemunerationVo.setClassTime(0);
        aggregateTeacherRemunerationVo.setLectureAmount(0);
        aggregateTeacherRemunerationVo.setStudentAmount(0);
        for(TeacherRemuneration teacherRemuneration : teacherRemunerationList ){

            aggregateTeacherRemunerationVo.setLectureAmount(aggregateTeacherRemunerationVo.getLectureAmount() + 1 );
            aggregateTeacherRemunerationVo.setStudentAmount(aggregateTeacherRemunerationVo.getStudentAmount() + teacherRemuneration.getStudentAmount());
            aggregateTeacherRemunerationVo.setClassTime(aggregateTeacherRemunerationVo.getClassTime() + teacherRemuneration.getClassTime());
            aggregateTeacherRemunerationVo.setAmount(aggregateTeacherRemunerationVo.getAmount().add( aggregateTeacherRemunerationVo.getAmount()));
        }

        return ReturnResult.success(aggregateTeacherRemunerationVo);
    }


    @ApiOperation("我的课酬和课时统计(按月)")
    @RequestMapping(value = "/myClassRemunerationOfMonth", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassRemunerationVo>> myClassRemunerationOfMonth(@RequestParam("year") int year, @RequestParam("month") int month  , HttpServletRequest request ) {

        String lastDayOfMonth = TimeUtils.getLastDayOfMonth(year, month);
        Date start  = Utils.parseDate(year + "-" + StringUtils.leftPad(String.valueOf(month),2,"0") + "-01 00:00","yyyy-MM-dd HH:mm");
        Date end = Utils.parseDate(lastDayOfMonth + " 23:59" ,"yyyy-MM-dd HH:mm" );
        List<TeacherRemuneration> teacherRemunerationList = teacherRemunerationService.findMyClassRemuneration(getTeacherId(request),start , end );
        Map<Long, ClassRemunerationVo> stat = toClassRemuneration(teacherRemunerationList);

        return ReturnResult.success(new ArrayList<ClassRemunerationVo>(stat.values()));
    }

    private Map<Long, ClassRemunerationVo> toClassRemuneration(List<TeacherRemuneration> teacherRemunerationList) {
        List<Long> classIds  = BeanUtils.toList(teacherRemunerationList,"classId");
        List<CourseClass> courseClassList = courseClassService.findByIds(classIds);
        Map<Long,CourseClass> courseClassMap = BeanUtils.toMap(courseClassList,"classId");
        Map<Long,ClassRemunerationVo> stat = new HashMap<>();
        //聚合
        for(TeacherRemuneration teacherRemuneration : teacherRemunerationList ){
            ClassRemunerationVo classRemunerationVo = stat.get(teacherRemuneration.getClassId());
            if(classRemunerationVo == null ){
                classRemunerationVo = new ClassRemunerationVo() ;
                classRemunerationVo.setClassTimes(0);
                classRemunerationVo.setLectureAmount(0);
                classRemunerationVo.setAmount(BigDecimal.ZERO);
                classRemunerationVo.setStudentAmount(0);
                classRemunerationVo.setCourseClass(courseClassMap.get(teacherRemuneration.getClassId()));
            }
            classRemunerationVo.setAmount(classRemunerationVo.getAmount().add(teacherRemuneration.getAmount()));
            classRemunerationVo.setClassTimes(classRemunerationVo.getClassTimes() + teacherRemuneration.getClassTime() );
            classRemunerationVo.setLectureAmount(classRemunerationVo.getLectureAmount() + 1 );
            classRemunerationVo.setStudentAmount(classRemunerationVo.getStudentAmount()+ teacherRemuneration.getStudentAmount() );
            stat.put(teacherRemuneration.getClassId() , classRemunerationVo );
        }
        return stat;
    }


    @ApiOperation("我的课酬总收入(按月)")
    @RequestMapping(value = "/myClassRemunerationAmountOfMonth", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<BigDecimal> myClassRemunerationAmountOfMonth(@RequestParam("year") int year, @RequestParam("month") int month  , HttpServletRequest request ) {
        String lastDayOfMonth = TimeUtils.getLastDayOfMonth(year, month);
        Date start  = Utils.parseDate(year + "-" + StringUtils.leftPad(String.valueOf(month),2,"0") + "-01 00:00","yyyy-MM-dd HH:mm");
        Date end = Utils.parseDate(lastDayOfMonth + " 23:59" ,"yyyy-MM-dd HH:mm" );
        List<TeacherRemuneration> teacherRemunerationList = teacherRemunerationService.findMyClassRemuneration(getTeacherId(request),start , end );
        BigDecimal bigDecimal = new BigDecimal(0) ;
        for(TeacherRemuneration teacherRemuneration : teacherRemunerationList ){
            bigDecimal = bigDecimal.add(teacherRemuneration.getAmount());
        }
        return ReturnResult.success(bigDecimal);
    }


    @ApiOperation("老师读统计")
    @RequestMapping(value = "/teacherContinueClassStat", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<TeacherContinueClassStat> teacherContinueClassStat(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {
        TeacherContinueClassStat teacherContinueClassStat = teacherContinueClassStatService.findTeacherContinueClassStat(periodId, getTeacherId(request));
        return ReturnResult.success(teacherContinueClassStat);
    }


    @ApiOperation("任教班级续读统计")
    @RequestMapping(value = "/classContinueClassStat", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassContinueClassStatVo>> classContinueClassStat(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {

        List<CourseClass> courseClassList = courseClassService.findCourseClassByPeriodIdTeacherId(periodId, getTeacherId(request));
        List<Long> classIds  = BeanUtils.toList(courseClassList,"classId");

        List<ContinueClassStat> continueClassStatList = continueClassStatService.findContinueClassStatByPeriodClassIds(periodId, classIds);

        List<Long> classIds2  = BeanUtils.toList(continueClassStatList,"classId") ;

        List<CourseClass> courseClassList1 = courseClassService.findByIds(classIds2);
        Map<Long , CourseClass> courseClassMap = BeanUtils.toMap(courseClassList1, "classId");

        List<ClassContinueClassStatVo> retList  = new ArrayList<>(continueClassStatList.size());
        for(ContinueClassStat continueClassStat : continueClassStatList ){
            retList.add(new ClassContinueClassStatVo(courseClassMap.get(continueClassStat.getClassId()), continueClassStat )) ;
        }
        return ReturnResult.success(retList);
    }


    @ApiOperation("班级续读详情")
    @RequestMapping(value = "/classContinueClassDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<ClassContinueClassDetailVo> classContinueClassDetail(@RequestParam("classId") Long classId , HttpServletRequest request ) {
        ContinueClassStat continueClassStat = continueClassStatService.findContinueClassStatByClassId(classId);

        List<Student> studentList = studentService.findByIds(Utils.toLongIds(continueClassStat.getStudentIds()));
        List<StudentContinueClassVo> retList = new ArrayList<>(studentList.size());
        for(Student student : studentList ){
            StudentContinueClassVo studentContinueClassVo = new StudentContinueClassVo();
            studentContinueClassVo.setStudentId(student.getStudentId());
            studentContinueClassVo.setStudentName(student.getName());
            studentContinueClassVo.setContinueClass(continueClassStat.getContinueClassStudentIds().contains(student.getStudentId().toString()));
            retList.add(studentContinueClassVo);
        }
        ClassContinueClassDetailVo classContinueClassDetailVo = new ClassContinueClassDetailVo();
        classContinueClassDetailVo.setStudentList(retList);
        classContinueClassDetailVo.setContinueClassStatVo(new ClassContinueClassStatVo(courseClassService.findById(classId), continueClassStat ));
        return ReturnResult.success(classContinueClassDetailVo);
    }

    @ApiOperation("学生详情")
    @RequestMapping(value = "/studentDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Student> studentDetail(@RequestParam("studentId") Long studentId , HttpServletRequest request ) {
        Student student = studentService.findById(studentId);
        return ReturnResult.success(student);
    }

    @ApiOperation("老师详情")
    @RequestMapping(value = "/teacherDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<TeacherDetailVo> teacherDetail(@RequestParam("teacherId") Long teacherId , HttpServletRequest request ) {
        Teacher teacher = teacherService.findById(teacherId);
        AreaTeam areaTeam = areaTeamService.findById(teacher.getAreaTeamId());
        BusTeam busTeam = busTeamService.findById(teacher.getBusTeamId());
        TeacherDetailVo teacherDetailVo = new TeacherDetailVo();
        teacherDetailVo.setAreaTeam(areaTeam);
        teacherDetailVo.setBusTeam(busTeam);
        teacherDetailVo.setTeacher(teacher);
        return ReturnResult.success(teacherDetailVo);
    }


    @ApiOperation("更新老师信息")
    @RequestMapping(value = "/updateTeacher", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> updateTeacher(@RequestParam("teacherId") Long teacherId ,@RequestParam(value = "avatarUrl" , required = false) String avatarUrl , @RequestParam(value = "tags", required = false) String tags , @RequestParam(value = "signature",required = false ) String signature, HttpServletRequest request ) {
        TeacherSaveOrUpdateVo teacherSaveOrUpdateVo = new TeacherSaveOrUpdateVo() ;
        teacherSaveOrUpdateVo.setTeacherId(teacherId);
        teacherSaveOrUpdateVo.setAvatarUrl(avatarUrl);
        teacherSaveOrUpdateVo.setTags(tags);
        teacherSaveOrUpdateVo.setSignature(signature);
        teacherService.saveOrUpdateTeacher(teacherSaveOrUpdateVo);
        return ReturnResult.success("OK");
    }


    @ApiOperation("续读率排名")
    @RequestMapping(value = "/continueClassRank", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<RankByContinueClassRankWithTeacherVo>> continueClassRank(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {
      //  Long areaTeamId  = getTeacher(request).getAreaTeamId();
        Teacher teacher=getTeacher(request);
        //List<RankByContinueClassVo> rankByContinueClassVoList = teacherContinueClassStatService.rank(areaTeamId, periodId);
        List<RankByContinueClassVo> rankByContinueClassVoList=mergeStudentRegDetailService.findTeacherContinueRankRate(teacher,periodId);
        List<RankByContinueClassVo> compareList = null ;
        Map<Long,RankByContinueClassVo> compareMap = new HashMap<>() ;
        String comparedDataJSON = (String)redisTemplate.opsForValue().get(String.format(KEY_PRE, teacher.getAreaTeamId(), periodId, "rankByContinueClass", compareDay()));
        if(StringUtils.isNotEmpty(comparedDataJSON)){
            compareList = JSONObject.parseObject(comparedDataJSON,new TypeReference<List<RankByContinueClassVo>>(){});
            compareMap = BeanUtils.toMap(compareList,"teacherId");
        }

        List<Long> teacherIds  = BeanUtils.toList(rankByContinueClassVoList,"teacherId");

        List<Teacher> teacherList = teacherService.findByIds(teacherIds);
        Map<Long,Teacher> teacherMap = BeanUtils.toMap(teacherList,"teacherId") ;

        List<RankByContinueClassRankWithTeacherVo> retList  = new ArrayList<>(teacherList.size()) ;

        for(RankByContinueClassVo vo : rankByContinueClassVoList ){
            RankByContinueClassRankWithTeacherVo teacherRankByContinueClassVo = new RankByContinueClassRankWithTeacherVo() ;
            BeanUtils.copyProperties(teacherRankByContinueClassVo,vo );
            teacherRankByContinueClassVo.setTeacher(teacherMap.get(vo.getTeacherId()));

            RankByContinueClassVo last = compareMap.get(vo.getTeacherId());

            if(last != null ){
                teacherRankByContinueClassVo.setLastRankNo(last.getRankNo());
            }

            retList.add(teacherRankByContinueClassVo);
        }
        return ReturnResult.success(retList);
    }

    @ApiOperation("课时排名")
    @RequestMapping(value = "/classTimeRank", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassTimeRankWithTeacherVo>> classTimeOrClassRemunerationRank(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {
        Long areaTeamId = getTeacher(request).getAreaTeamId();
        List<ClassTimeRankVo> classTimeRankVoList = teacherRemunerationService.classTimeRank( areaTeamId, periodId);

        List<ClassTimeRankVo> compareList = null ;
        Map<Long,ClassTimeRankVo> compareMap = new HashMap<>() ;
        String comparedDataJSON = (String)redisTemplate.opsForValue().get(String.format(KEY_PRE, areaTeamId, periodId, "classTime", compareDay()));
        if(StringUtils.isNotEmpty(comparedDataJSON)){
            compareList = JSONObject.parseObject(comparedDataJSON,new TypeReference<List<ClassTimeRankVo>>(){});
            compareMap = BeanUtils.toMap(compareList,"teacherId");
        }

        List<Long> teacherIds  = BeanUtils.toList(classTimeRankVoList,"teacherId");
        List<Teacher> teacherList = teacherService.findByIds(teacherIds);
        Map<Long,Teacher> teacherMap = BeanUtils.toMap(teacherList,"teacherId") ;

        List<ClassTimeRankWithTeacherVo> retList  = new ArrayList<>(teacherList.size()) ;

        for(ClassTimeRankVo vo : classTimeRankVoList ){
            ClassTimeRankWithTeacherVo teacherClassTimeRankVo = new ClassTimeRankWithTeacherVo() ;
            BeanUtils.copyProperties(teacherClassTimeRankVo,vo );

            teacherClassTimeRankVo.setTeacher(teacherMap.get(vo.getTeacherId()));

            ClassTimeRankVo last = compareMap.get(vo.getTeacherId());
            if(last != null){
                teacherClassTimeRankVo.setLastRankNo(last.getRankNo());
            }

            retList.add(teacherClassTimeRankVo);
        }
        return ReturnResult.success(retList);
    }

    @ApiOperation("课酬或者科数排名")
    @RequestMapping(value = "/classRemunerationRank", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassRemunerationRankWithTeacherVo>> classRemunerationRank(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {
       // Long areaTeamId = getTeacher(request).getAreaTeamId();
        Teacher teacher=getTeacher(request);
       // List<ClassRemunerationRankVo> classRemunerationRankVoList = teacherRemunerationService.classRemunerationRank(areaTeamId, periodId);
        List<ClassRemunerationRankVo> classRemunerationRankVoList=mergeStudentRegDetailService.findRegNumOrRemuneration(teacher,periodId);
        List<ClassRemunerationRankVo> compareList = null ;
        Map<Long,ClassRemunerationRankVo> compareMap = new HashMap<>() ;
        String comparedDataJSON = (String)redisTemplate.opsForValue().get(String.format(KEY_PRE, teacher.getAreaTeamId(), periodId, "classRemuneration", compareDay()));
        if(StringUtils.isNotEmpty(comparedDataJSON)){
            compareList = JSONObject.parseObject(comparedDataJSON,new TypeReference<List<ClassRemunerationRankVo>>(){});
            compareMap = BeanUtils.toMap(compareList,"teacherId");
        }

        List<Long> teacherIds  = BeanUtils.toList(classRemunerationRankVoList,"teacherId");
        List<Teacher> teacherList = teacherService.findByIds(teacherIds);
        Map<Long,Teacher> teacherMap = BeanUtils.toMap(teacherList,"teacherId") ;

        List<ClassRemunerationRankWithTeacherVo> retList  = new ArrayList<>(teacherList.size()) ;

        for(ClassRemunerationRankVo vo : classRemunerationRankVoList ){
            ClassRemunerationRankWithTeacherVo teacherClassRemunerationRankVo = new ClassRemunerationRankWithTeacherVo() ;
            BeanUtils.copyProperties(teacherClassRemunerationRankVo,vo );
            teacherClassRemunerationRankVo.setTeacher(teacherMap.get(vo.getTeacherId()));

            ClassRemunerationRankVo last = compareMap.get(vo.getTeacherId());
            if(last != null ){
                teacherClassRemunerationRankVo.setLastRankNo(last.getRankNo());
            }

            retList.add(teacherClassRemunerationRankVo);
        }
        return ReturnResult.success(retList);
    }


    @ApiOperation("咨询师科数统计（营运指标）")
    @RequestMapping(value = "/findCounselorComletionRate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<CounselorRateVo>> findCounselorComletionRate( @ModelAttribute PeriodQueryRegVo periodQueryRegVo,  @RequestParam(value = "periodId") Long periodId,  HttpServletRequest request) {
        Teacher teacher=getTeacher(request);
        TeacherQueryVo teacherQueryVo=new TeacherQueryVo();
        teacherQueryVo.setTeacherId(teacher.getTeacherId());
        periodQueryRegVo.setChargingStatus(2);
        //periodQueryRegVo.setLectureNum(5);
        periodQueryRegVo.setRegStatus(0);
        Page<CounselorRateVo> page = indexStatisticsService.findCounselorComletionRateVoPage(periodQueryRegVo,teacherQueryVo,null,Arrays.asList(periodId),1,10);
        if (page.getRecords()!=null&&page.getRecords().size()>0){
            return ReturnResult.success(page.getRecords().get(0));
        }
        return ReturnResult.success();
    }

    @ApiOperation("初三班主任续读")
    @RequestMapping(value = "/findOneAcademicAdvisorData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<AcademicAdvisorDataVo> findOneAcademicAdvisorData( @RequestParam("startDate") Date startDate,@RequestParam("endDate")Date endDate, HttpServletRequest request) {
        Teacher teacher=getTeacher(request);
        if (endDate!=null){
            endDate=TimeUtils.changeOneDateLastTime(endDate);
        }
        TeacherQueryVo teacherQueryVo=new TeacherQueryVo();
        teacherQueryVo.setTeacherId(teacher.getTeacherId());
        Page<AcademicAdvisorDataVo> academicAdvisorDataPage = indexStatisticsService.findAcademicAdvisorData(teacher.getAreaTeamId(), teacherQueryVo, startDate, endDate, 1, 1);
        List<AcademicAdvisorDataVo> academicAdvisorDataVoList=academicAdvisorDataPage.getRecords();
        if (academicAdvisorDataVoList!=null && academicAdvisorDataVoList.size()>0){
            return ReturnResult.success(academicAdvisorDataVoList.get(0));
        }

        return ReturnResult.success("");
    }




    @ApiOperation("学生人次排名")
    @RequestMapping(value = "/studentAmountRank", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<StudentAmountRankWithTeacherVo>> studentAmountRank(@RequestParam("periodId") Long periodId , HttpServletRequest request ) {
        //Long areaTeamId = getTeacher(request).getAreaTeamId();
        //List<StudentAmountRankVo> studentAmountRankVoList = teacherRemunerationService.studentAmountRank(areaTeamId, periodId);
        Teacher teacher=getTeacher(request);
        List<StudentAmountRankVo> studentAmountRankVoList=mergeStudentRegDetailService.findStudentAmountRank(teacher,periodId);
        List<StudentAmountRankVo> compareList = null ;
        Map<Long,StudentAmountRankVo> compareMap = new HashMap<>() ;
        String comparedDataJSON = (String)redisTemplate.opsForValue().get(String.format(KEY_PRE, teacher.getAreaTeamId(), periodId, "studentAmount", compareDay()));
        if(StringUtils.isNotEmpty(comparedDataJSON)){
            compareList = JSONObject.parseObject(comparedDataJSON,new TypeReference<List<StudentAmountRankVo>>(){});
            compareMap = BeanUtils.toMap(compareList,"teacherId");
        }

        List<Long> teacherIds  = BeanUtils.toList(studentAmountRankVoList,"teacherId");
        List<Teacher> teacherList = teacherService.findByIds(teacherIds);
        Map<Long,Teacher> teacherMap = BeanUtils.toMap(teacherList,"teacherId") ;

        List<StudentAmountRankWithTeacherVo> retList  = new ArrayList<>(teacherList.size()) ;

        for(StudentAmountRankVo vo : studentAmountRankVoList ){
            StudentAmountRankWithTeacherVo teacherStudentAmountRankVo = new StudentAmountRankWithTeacherVo() ;
            BeanUtils.copyProperties(teacherStudentAmountRankVo,vo );
            teacherStudentAmountRankVo.setTeacher(teacherMap.get(vo.getTeacherId()));

            StudentAmountRankVo last = compareMap.get(vo.getTeacherId());
            if(last != null ){
                teacherStudentAmountRankVo.setLastRankNo(last.getRankNo());
            }
            retList.add(teacherStudentAmountRankVo);
        }
        return ReturnResult.success(retList);
    }


    @ApiOperation("我的名次")
    @RequestMapping(value = "/myRankNo", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<TeacherRankNoVo> myRankNo(@RequestParam("periodId") final Long periodId , HttpServletRequest request ) throws InterruptedException, ExecutionException {
        final Teacher teacher = getTeacher(request);
        TeacherRankNoVo teacherRankNoVo = new TeacherRankNoVo();

        List<Future<Integer>> futureResults = Threads.invokeAll(Arrays.asList(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                RankByContinueClassVo rankByContinueClassVo = teacherContinueClassStatService.myRank(teacher.getAreaTeamId(), periodId, teacher.getTeacherId());
                return rankByContinueClassVo == null ? null : rankByContinueClassVo.getRankNo();
            }
        }, new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                ClassRemunerationRankVo classRemunerationRankVo = teacherRemunerationService.myClassRemunerationRank(teacher.getAreaTeamId(), periodId, teacher.getTeacherId());
                return classRemunerationRankVo == null ? null : classRemunerationRankVo.getRankNo();

            }
        }, new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                StudentAmountRankVo studentAmountRankVo = teacherRemunerationService.myStudentAmountRank(teacher.getAreaTeamId(), periodId, teacher.getTeacherId());
                return studentAmountRankVo == null ? null : studentAmountRankVo.getRankNo();
            }
        }));

        teacherRankNoVo.setRankNoContinueClass(futureResults.get(0).get());
        teacherRankNoVo.setRankNoClassRemuneration(futureResults.get(1).get());
        teacherRankNoVo.setRankNoStudentAmount(futureResults.get(2).get());
        return ReturnResult.success(teacherRankNoVo);
    }








    private List<CourseClassWithTeacherVo> fillTeacher(List<CourseClass> courseClassList) {
        List<Long> teacherIds  = new  ArrayList<>(courseClassList.size());
        for(CourseClass courseClass : courseClassList ){

            if(courseClass.getTeacherId() != null){
                teacherIds.add(courseClass.getTeacherId());
            }
        }

        List<Teacher> teacherList = teacherIds.isEmpty() ? Collections.EMPTY_LIST : teacherService.findByIds(teacherIds);
        Map<Long,Teacher> teacherMap = BeanUtils.toMap(teacherList,"teacherId");
        List<CourseClassWithTeacherVo> retList = new ArrayList<>(courseClassList.size());
        for(CourseClass courseClass : courseClassList ){
            CourseClassWithTeacherVo courseClassWithTeacherVo = new CourseClassWithTeacherVo();
            BeanUtils.copyProperties(courseClassWithTeacherVo , courseClass);
            if(courseClass.getTeacherId() != null ){
                Teacher teacher = teacherMap.get(courseClass.getTeacherId());
                courseClassWithTeacherVo.setTeacher(teacher);
            }
            retList.add(courseClassWithTeacherVo);
        }

        return retList ;
    }


    private String compareDay(){
        return Utils.formatDate(TimeUtils.now(),"yyyy-MM-dd");
    }

    @ApiOperation("任课老师班级退费情况")
    @RequestMapping(value = "/findTeacherPeriodRefundDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<TeacherPeriodRefundDetailVo>> findTeacherPeriodRefundDetail(@RequestParam("periodId")long periodId, HttpServletRequest request ) {
        final Teacher teacher = getTeacher(request);
        List<TeacherPeriodRefundDetailVo> teacherPeriodRefundDetailVoList = mergeStudentRegDetailService.findTeacherPeriodRefundDetail(teacher.getTeacherId(), periodId);
        return ReturnResult.success(teacherPeriodRefundDetailVoList);
    }

    @ApiOperation("班级退费情况")
    @RequestMapping(value = "/classRefundDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<StudentRefund>> classRefundDetail(@RequestParam("classId")long classId, HttpServletRequest request ) {
        List<StudentRefund> studentRefundList=studentRefundService.findStudentRefundByClassIdStatus(classId,1);
        return ReturnResult.success(studentRefundList);
    }

    @ApiOperation("查询课程列表")
    @RequestMapping(value = "/outCourseClassList" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<SimpleCourseClass>> outCourseClassList(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, OuterCourseClassQueryVo outerCourseClassQueryVo, HttpServletRequest request) {
        final Teacher teacher=this.getTeacher(request);
        outerCourseClassQueryVo.setAreaTeamId(teacher.getAreaTeamId());
        List<SimpleCourseClass> outerCourseClasses=outerCourseClassService.findOuterCourseClassByCondition(outerCourseClassQueryVo,pageNo,pageSize);
        return ReturnResult.success(outerCourseClasses);
    }



    @ApiOperation("加入推荐单")
    @RequestMapping(value = "/addRecommendRecord" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> addRecommendRecord( @RequestParam("classId")long classId, HttpServletRequest request) {
        final Teacher teacher = getTeacher(request);
        recommendRecordService.addRecommendRecord(teacher.getTeacherId(),1,classId);
        return ReturnResult.success("ok");
    }

    @ApiOperation("删除推荐单")
    @RequestMapping(value = "/deleteRecommendRecords" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> deleteRecommendRecords(@RequestParam("recommendIds")String recommendIds, HttpServletRequest request) {
        final Teacher teacher = getTeacher(request);
        recommendRecordService.deleteRecommendRecordByUserIdRecommendIds(teacher.getTeacherId(),Utils.toLongIds(recommendIds));
        return ReturnResult.success("ok");
    }

    @ApiOperation("我的推荐单")
    @RequestMapping(value = "/recommendRecords" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<RecommendRecordDetailVo>> recommendRecords(HttpServletRequest request) {
        final Teacher teacher = getTeacher(request);
        List<RecommendRecordDetailVo> recommendRecordDetailList = recommendRecordService.findRecommendRecordDetailList(teacher.getTeacherId());
        return ReturnResult.success(recommendRecordDetailList);
    }




    @ApiOperation("课程过滤条件配置")
    @RequestMapping(value = "/courseFilterCondConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<CourseFilterCondConfig> courseFilterCondConfig(HttpServletRequest request ) {
        final Teacher teacher = getTeacher(request);
        CourseFilterCondConfig courseFilterCondConfig = configService.findCourseFilterCondConfigFromCache(teacher.getAreaTeamId());

        if(courseFilterCondConfig != null ){
            for(CourseFilterCondConfig.Item item : courseFilterCondConfig.getPeriods() ){
                item.put("teachers" ,Collections.EMPTY_LIST );
            }
        }

        return ReturnResult.success(courseFilterCondConfig);
    }



    @ApiOperation("课程过滤条件配置(老师)")
    @RequestMapping(value = "/teacherOfCourseFilterCondConfig", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<CourseFilterCondConfig.Item> > teacherOfCourseFilterCondConfig(@RequestParam("areaTeamId") Long areaTeamId ,@RequestParam(value = "periodId" , required = false ) String periodId ) {
        CourseFilterCondConfig courseFilterCondConfig = configService.findCourseFilterCondConfigFromCache(areaTeamId);

        List<CourseFilterCondConfig.Item> list = Collections.EMPTY_LIST ;
        if(courseFilterCondConfig != null ){
            for(CourseFilterCondConfig.Item item : courseFilterCondConfig.getPeriods() ){
                if(StringUtils.isNotEmpty(periodId)){
                    if(periodId.equals(item.get("value"))){
                        list = (List<CourseFilterCondConfig.Item>) item.get("teachers");
                        break;
                    }
                }else{

                    if(StringUtils.isEmpty((String)item.get("value"))){
                        list = (List<CourseFilterCondConfig.Item>) item.get("teachers");
                        break;
                    }
                }
            }
        }
        return ReturnResult.success(list);
    }


    @ApiOperation("活动列表")
    @RequestMapping(value = "/activityCampusList" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ActivityCampusDetailVo>> activityCampusList(@ModelAttribute ActivityCampusQueryVo activityCampusQueryVo,@RequestParam(value = "pageNo",defaultValue = "1") int pageNo,@RequestParam(value = "pageSize",defaultValue = "20")int pageSize, HttpServletRequest request) {
        DataPermission dataPermission=this.getDataPermission(request);
        Page<ActivityCampusDetailVo> activityCampusDetailVoPage = activityCampusService.findActivityTargetPageByQueryVo(dataPermission, activityCampusQueryVo, pageNo, pageSize);
        return ReturnResult.success(activityCampusDetailVoPage);
    }

    @ApiOperation("场次")
    @RequestMapping(value = "/activityCampusSession" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ActivityCampusSession>> activityCampusSession(@RequestParam("activityCampusId")long activityCampusId , HttpServletRequest request) {
        List<ActivityCampusSession> activityCampusSessionList = activityCampusSessionService.findSessionByActivityCampusId(activityCampusId);
        return ReturnResult.success(activityCampusSessionList);
    }

    @ApiOperation("场次签到信息")
    @RequestMapping(value = "/activityCampusSessionMsg" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<ActivitySessionNumVo> activityCampusSessionMsg(@RequestParam("activityCampusSessionId")long activityCampusSessionId , HttpServletRequest request) {
        ActivitySessionNumVo activitySessionNumVo=activityRegSituationService.findActivitySessionNum(activityCampusSessionId);
        return ReturnResult.success(activitySessionNumVo);
    }

    @ApiOperation("需要咨询的学生")
    @RequestMapping(value = "/sessionDiagnosisStudents" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult< List<ActivityRegSituation>> sessionDiagnosisStudents(@RequestParam("activityCampusSessionId")long activityCampusSessionId , HttpServletRequest request) {
        List<ActivityRegSituation> diagnosisStudent = activityRegSituationService.findDiagnosisStudent(activityCampusSessionId);
        return ReturnResult.success(diagnosisStudent);
    }

    @ApiOperation("活动目标")
    @RequestMapping(value = "/activityCampusTarget" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<ActivityTarget> activityCampusTarget(@RequestParam("activityId")long activityId,@RequestParam("campusId")long campusId , HttpServletRequest request) {
        ActivityTarget activityTarget = activityTargetService.findActivityTargetByActivityIdCampusId(activityId, campusId);
        return ReturnResult.success(activityTarget);
    }


    @ApiOperation("活动信息")
    @RequestMapping(value = "/activityCampusMsg" , method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ReturnResult<ActivityNumVo> activityCampusMsg(@RequestParam("activityCampusId")long activityCampusId, HttpServletRequest request) {
        ActivityNumVo activityNum = activityRegSituationService.findActivityNum(activityCampusId);
        return ReturnResult.success(activityNum);
    }

}
